package org.raymond.icloud.common.core.util.http;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class CachedRequestWrapper extends HttpServletRequestWrapper {
    private ByteArrayOutputStream cachedBytes;

    public CachedRequestWrapper(HttpServletRequest request) throws IOException{
        super(request);
        getInputStream();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if(cachedBytes==null){
            cacheInputStream();
        }
        // 每次返回一份COPY
        return new CachedServletInputStream(cachedBytes.toByteArray());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    private void cacheInputStream() throws IOException {
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }

    public byte[] getContentAsByteArray() {
        return this.cachedBytes.toByteArray();
    }

    public static class CachedServletInputStream extends ServletInputStream{
        private final ByteArrayInputStream inputStream;

        public CachedServletInputStream(byte[] buf) {
            inputStream = new ByteArrayInputStream(buf);
        }
        public boolean isFinished() {
            return inputStream.available()==0;
        }
        public boolean isReady() {
            return true;
        }
        public void setReadListener(ReadListener listener) {
        }
        public int read() throws IOException {
            return inputStream.read();
        }
    }
}
